<template>
  <el-card>
    <template #header>
      <el-button type="primary" size="small" @click="$parent.show = 'table'">返回
      </el-button>
    </template>
    <div style="">
      <el-tabs
        type="border-card"
        :stretch="stretch"
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane label="用户信息" name="first" />
        <el-tab-pane label="残疾证办理" name="second" />
        <el-tab-pane label="临时救助" name="third" />
        <el-tab-pane label="精准康复" name="fourth" />
        <el-tab-pane label="家庭无障碍改造" name="fifth" />
        <el-tab-pane label="技能培训" name="jnpx" />
        <el-tab-pane label="享受政策" name="sixth" />

        <el-descriptions v-loading="loading" style="padding:0 10vw" v-if="activeName==='first'" :column="2" border>
          <el-descriptions-item label="姓名">{{
                                           disInfo.name
                                           }}
          </el-descriptions-item>
          <el-descriptions-item label="头像" v-if="disInfo.avatar">
            <el-image
              style="width:90px;height: 90px"
              :src="getImage(JSON.parse(disInfo.avatar)[0].value)"
              :preview-src-list="[getImage(JSON.parse(disInfo.avatar)[0].value)]"
            />
          </el-descriptions-item>

          <el-descriptions-item label="所在地">
            <span v-if="address">
              {{ address }}
            </span>
            <i v-else class="el-icon-loading"></i>
          </el-descriptions-item>
          <el-descriptions-item label="姓别">{{
                                           disInfo.sex
                                           }}
          </el-descriptions-item>
          <el-descriptions-item label="民族">{{
                                           disInfo.nation
                                           }}
          </el-descriptions-item>
          <el-descriptions-item label="婚姻状况">{{
                                             disInfo.marital
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="出生年月">{{
                                             disInfo.birth
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="籍贯">{{
                                           disInfo.nativePlace
                                           }}
          </el-descriptions-item>
          <el-descriptions-item label="文化程度">{{
                                             disInfo.culture
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">{{
                                             disInfo.idCard
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="户籍地址">{{
                                             disInfo.permanent
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="邮编">{{
                                           disInfo.postcode
                                           }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">{{
                                             disInfo.phone
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="监护人姓名">{{
                                              disInfo.tutelageName
                                              }}
          </el-descriptions-item>
          <el-descriptions-item label="与申请人关系">{{
                                               disInfo.relation
                                               }}
          </el-descriptions-item>
          <el-descriptions-item label="监护人联系电话">{{
                                                disInfo.tutelagePhone
                                                }}
          </el-descriptions-item>
          <el-divider content-position="left">残疾证信息</el-divider>
          <el-descriptions-item label="初次办证日期">{{
                                               disInfo.disabledCardDate
                                               }}
          </el-descriptions-item>
          <el-descriptions-item label="残疾证号">{{
                                             disInfo.disabledCard
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="残疾类别">{{
                                             disInfo.disabledType | setType(getDictionary("DIS_TYPE"))
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="残疾等级">{{
                                             disInfo.disabledLevel | keyText("DIS_LEVEL")
                                             }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证正面" v-if="disInfo.idCardPositive">
            <el-image
              style="width:150px;height: 90px"
              :src="getImage(JSON.parse(disInfo.idCardPositive)[0].value)"
              :preview-src-list="[getImage(JSON.parse(disInfo.idCardPositive)[0].value)]"
            />
          </el-descriptions-item>
          <el-descriptions-item label="身份证背面" v-if="disInfo.idCardNegative">
            <el-image
              style="width:150px;height: 90px"
              :src="getImage(JSON.parse(disInfo.idCardNegative)[0].value)"
              :preview-src-list="[getImage(JSON.parse(disInfo.idCardNegative)[0].value)]"
            />
          </el-descriptions-item>
        </el-descriptions>
        <div v-loading="loading" v-else>
          <el-row v-if="activeName==='sixth'">
            <el-col>
              <el-button
                type="primary"
                @click="policy"
                size="small"
                icon="el-icon-plus"
                style="margin-bottom:10px;margin-right:10px;float: right"
                v-if="$route.name==='manage'"
              >
                新增享受政策
              </el-button>
            </el-col>
          </el-row>
          <page-table
            ref="multipleSelection"
            :page-data="pageData"
            :do-get-page-data="getPageData"
          >
            <el-table-column type="index" label="编号" width="80" align="center" />
            <el-table-column
              v-for="(column,index) in columnList"
              :key="index"
              :label="column.label"
              :prop="column.prop"
              align="center"
              :width="column.width || ''"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span v-if="column.enum">
                  {{ column.enum[scope.row[column.prop]] }}
                </span>
                <span v-else>{{scope.row[column.prop]}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="管理"
              width="150"
              align="center"
              fixed="right"
              v-if="activeName==='sixth' && $route.name==='manage'"
            >
              <template slot-scope="scope">
                <el-tooltip content="编辑" placement="top">
                  <el-button
                    type="button"
                    size="mini"
                    icon="el-icon-edit"
                    @click="edit(scope.row)"
                  >
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    type="button"
                    size="mini"
                    icon="el-icon-delete"
                    @click="del(scope.row)"
                  >
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </page-table>
        </div>
      </el-tabs>
    </div>

    <el-dialog :visible.sync="policyShow" v-if="policyShow" title="新增享受政策" @close="close">
      <el-form
        ref="form"
        :model="policyForm"
        :rules="policyRule"
        label-width="auto"
        label-suffix=":"
        style="padding:10px 20px 0"
      >
        <el-form-item label="政策类型" prop="type">
          <el-select v-model="policyForm.type" placeholder="请选择政策类型">
            <el-option
              v-for="item in getDictionary('PERSON_WEAL')"
              :key="item.keyword"
              :label="item.label"
              :value="item.keyword"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="政策名称" prop="name">
          <el-input placeholder="请输入政策名称" v-model="policyForm.name" />
        </el-form-item>
        <el-form-item label="政策内容" prop="content">
          <el-input
            type="textarea"
            :autosize="{minRows:3}"
            placeholder="请输入政策内容"
            v-model="policyForm.content"
          />
        </el-form-item>
        <el-form-item label="附件" prop="files">
          <el-upload
            class="upload"
            drag
            :action="url"
            :headers="headers"
            multiple
            :on-success="successHandle"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :on-preview="previewDetail"
            :limit="10"
            :file-list="fileList"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="获得时间" prop="wealTime">
          <el-date-picker
            v-model="policyForm.wealTime"
            type="date"
            placeholder="选择日期"
            format="yyyy年MM月dd日"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="surePolicy">确认</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  name: "manageInfo",
  props: {
    disInfo: {
      type: Object
    },
    active: {
      type: String,
      default: 'first'
    }
  },
  data() {
    return {
      loading: false, //加载中开关
      stretch: true, //标签的宽度是否自撑开
      labelStyle: "padding:0 10vw",  //标签整体宽度
      fileList: [],
      url: window.api.sysUploadUrl + '?path=disabled',
      filePath: "",
      headers: {
        userRole: "ADMIN",
        token: sessionStorage.getItem("token")
      },
      policyForm: {},
      policyRule: {
        type: [{ required: true, message: "请选择政策类型", trigger: "blur" }],
        name: [{ required: true, message: "请选择政策名称", trigger: "blur" }],
      },
      site: [],
      address: "",
      activeName: 'first',
      pageData: {},
      searchDto: {
        pageIndex: 1,
        pageSize: 10
      },
      columnList: [],
      api: null,
      applianceApplicationStatus: {
        '-2': "鉴定机构驳回",
        '-1': "残联驳回",
        0: "未申请",
        1: "待选择鉴定机构",
        2: "鉴定机构审核中",
        3: "残联审核中",
        4: "待上传财政资料",
        5: "备货中",
        6: "待评价",
        7: "已评价",
      },
      completedStatus: {
        0: "未完成",
        1: "已完成",
      },
      policyShow: false
    };
  },
  watch: {
    active: {
      handler(val) {
        this.activeName = val
        if (val === 'sixth') {
          this.handlePolicy()
        }
      },
      immediate: true
    }
  },
  methods: {
    del({ id }) {
      this.$confirm("确认删除?", "提示", { type: "warning" }).then(() => {
        this.API.deleteDisabledPersonWealById({ id }).then(ret => {
          this.success("删除成功!");
          this.getPageData();
        });
      });
    },
    edit({ id }) {
      this.API.getDisabledPersonWealById({ id }).then(res => {
        this.policyForm = res.data
        if (this.policyForm.files) {
          const files = JSON.parse(this.policyForm.files)
          for (let i = 0; i < files.length; i++) {
            this.fileList.push({ name: files[i].fileName, url: files[i].fileName, id: files[i].id });
          }
        }
        this.policyShow = true
      })
    },
    surePolicy() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          Object.assign(this.policyForm, { userId: this.disInfo.userId })
          this.API.addOrUpdateDisabledPersonWeal({ body: this.policyForm }).then(ret => {
            this.success('操作成功')
            this.getPageData()
            this.close()
          })
        }
      })
    },
    close() {
      this.policyForm = {}
      this.fileList = []
      this.$refs.form.resetFields()
      this.policyShow = false
    },
    previewDetail(file) {
      const url = file.response ? file.response.id : file.id
      this.openTabPage(
        window.api.preFile +
        "?url=" +
        window.api.secretFilePreview +
        url +
        "?token=" +
        window.sessionStorage.getItem("token")
      );
    },
    successHandle(res, file, fileList) {
      this.policyForm.files = "";
      let ids = [];
      fileList.map(item => {
        if (item.response && item.response.id) {
          ids.push(item.response);
        } else {
          ids.push({
            id: item.id,
            fileName: item.name
          });
        }
      });
      this.policyForm.files = JSON.stringify(ids);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 10 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove(file, fileList) {
      this.policyForm.files = "";
      let ids = [];
      fileList.map(item => {
        if (item.response && item.response.id) {
          ids.push(item.response);
        } else {
          ids.push({
            id: item.id,
            fileName: item.name
          });
        }
      });
      this.policyForm.files = ids.length ? JSON.stringify(ids) : '';
    },
    // 新增享受政策
    policy() {
      this.policyShow = true
    },
    getPageData(val) {
      this.loading = true
      Object.assign(this.searchDto, val)
      this.API[this.api](this.searchDto).then(ret => {
        this.pageData = ret.data
        this.loading = false
      })
    },
    handleClick(v) {
      this.searchDto = { pageIndex: 1, pageSize: 10 }
      this.loading = false
      switch (v.name) {
        case 'first':
          this.labelStyle = "padding:0 10vw"
          this.stretch = true
          break

        case 'second':
        case 'third':
          this.api = 'getInstanceDataList'
          this.columnList = v.name === 'second'
            ? [
              { label: '姓名', prop: "name" },
              { label: '残疾类别', prop: "disabled_type", enum: this.getDictionary('DIS_TYPE', 'map') },
              { label: '残疾级别', prop: "disabled_level", enum: this.getDictionary('DIS_LEVEL', 'map') },
              { label: '申请类型', prop: "apply_type", enum: this.getDictionary('APPLY_TYPE', 'map') },
              { label: '申请时间', prop: "create_time" },
              { label: '监护人姓名', prop: "link_name" },
              { label: '监护人电话', prop: "link_phonenumber" },
              { label: '当前状态', prop: "completed", enum: this.completedStatus },
            ]
            : [
              { label: '姓名', prop: "name" },
              { label: '联系电话', prop: "mobile" },
              { label: '申请备注', prop: "reason" },
              { label: '申请时间', prop: "create_time" },
              { label: '当前状态', prop: "completed", enum: this.completedStatus },

            ]
          this.getPageData({
            userId: this.disInfo.userId,
            flowId: v.name === 'second'
              ? 'flow-25278d489d914aba8a54f96165e06ad4'
              : 'flow-531af866a8b34305878e22f7b65d51d7'
          })
          this.labelStyle = ""
          this.stretch = true
          break

        case 'fourth':
          this.api = 'getAssistEquApplyInfoDetailList'
          this.columnList = [
            { label: '康复活动名称', prop: 'assistActivityTitle' },
            { label: '康复类型', prop: 'applyType' },
            { label: '康复内容', prop: 'assistEquName' },
            { label: '康复原因', prop: 'applyReason' },
            { label: '申请时间', prop: 'applyTime' },
            { label: '当前状态', prop: 'status', enum: this.applianceApplicationStatus },
          ]
          this.getPageData({ userId: this.disInfo.userId })
          this.labelStyle = ""
          this.stretch = true
          break

        case 'fifth':
          this.api = 'getDetailList'
          this.columnList = [
            { label: '无障碍改造标题', prop: 'remouldName', width: 300 },
            { label: '联系人', prop: 'linkman' },
            { label: '联系方式', prop: 'linkmanPhone' },
            { label: '改造地址', prop: 'address' },
            { label: '改造内容', prop: 'content' },
            { label: '创建时间', prop: 'createTime' },
            { label: '当前状态', prop: 'status', enum: this.getDictionary('BARRIER_FREE_STATUS', 'map') },
          ]
          this.getPageData({ userId: this.disInfo.userId })
          this.labelStyle = ""
          this.stretch = true
          break

        case 'sixth':
          this.handlePolicy()
          break
        case 'jnpx':
          this.columnList = [
            { label: '培训主题', prop: 'title' },
            { label: '培训内容', prop: 'content' },
            { label: '培训地点', prop: 'site' },
            { label: '创建时间', prop: 'createTime' },
            { label: '开始时间', prop: 'startTime' },
            { label: '结束时间', prop: 'endTime' },
          ]
          this.api = 'getSkillTrainingPageList'
          this.getPageData({ userId: this.disInfo.userId })
          this.labelStyle = ""
          this.stretch = true
          break
      }
    },

    handlePolicy() {
      this.columnList = [
        { label: '政策名称', prop: 'name' },
        { label: '政策类型', prop: 'type', enum: this.getDictionary('PERSON_WEAL', 'map') },
        { label: '政策内容', prop: 'content' },
        { label: '获得时间', prop: 'wealTime' },
        { label: '创建时间', prop: 'createTime' },
      ]
      this.api = 'getDisabledPersonWealPageList'
      this.getPageData({ userId: this.disInfo.userId })
      this.labelStyle = ""
      this.stretch = true
    },

    getImage(url) {
      return window.api.image + '/' + url
    },

    getAreaName(lv, ls) {
      let query = { level: lv, pid: ls[lv - 1] };
      this.API.getSysAreaByLevelAndPid(query).then(ret => {
        if (ret.data.length == 0) return this.setAreaName();
        ret.data.map(i => {
          if (i.id == ls[lv]) {
            this.site.push(i.name);
          }
        });
        this.getAreaName(lv + 1, ls);
      });
    },
    setAreaName() {
      this.address = this.site.join("/");
    }
  },
  created() {
    let { province, city, district, street, committee } = this.disInfo;
    let tem = [0, province, city, district, street, committee].map(i => +i);
    this.getAreaName(1, tem);
  },
  filters: {
    setType(val, ts) {
      ts.map(i => {
        if (val.indexOf(i.keyword) > -1) {
          val = val.replace(i.keyword, i.label);
        }
      });
      return val;
    }
  }
};
</script>
<style scoped lang="scss">
  ::v-deep .el-tabs__item {
    font-size: 16px;
  }
</style>
